package com.taxi.driver.module.amap.assist;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.core.LatLonPoint;
import com.taxi.driver.R;
import com.taxi.driver.common.AppConfig;
import com.taxi.driver.config.DriverType;
import com.taxi.driver.data.entity.Car;
import com.taxi.driver.data.user.UserRepository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MapUtils {
    //小车的集合
    private Map<String, SmoothMoveMarker> mObjMarkerMap = new HashMap<>();
    //小车最后的位置
    private Map<String, Node> mObjLastLatlngMap = new HashMap<>();
    // 车的移动动画
    public static final int DEF_CAR_ANIMATION_FRAME_COUNT = 4;

    private static final Random sRandom = new Random();

    private static float random(float howsmall, float howbig) {
        if (howsmall >= howbig) return howsmall;
        return sRandom.nextFloat() * (howbig - howsmall) + howsmall;
    }

    /**
     * 添加小车
     *
     * @param obj
     */
    private void addCar(Car obj, AMap map) {
        if (obj == null) {
            return;
        }

        //判断当前车辆是否已经存，如果已存在，先移除
        if (mObjMarkerMap.containsKey(obj.getId())) {
            mObjMarkerMap.get(obj.getId()).destroy();
            removeCar(obj.getId());
        }

        //汽车标志
        SmoothMoveMarker marker = new SmoothMoveMarker(map);
        marker.setDescriptor(BitmapDescriptorFactory.fromResource(obj.getResId() == 0 ? R.drawable.map_icon_car : obj.getResId()));
        List<LatLng> latLngs = new ArrayList<>();
        latLngs.add(new LatLng(obj.getLat(), obj.getLng()));
        marker.setPoints(latLngs);
        //marker.getMarker().setRotateAngle(random(0, 360f));
        marker.getMarker().setRotateAngle(obj.getAngle());
        marker.startSmoothMove();
        marker.getMarker().setObject(obj);

        //判断是否显示气泡
        if (obj.isShowInfoWindow()) {
            marker.getMarker().showInfoWindow();
        } else {
            marker.getMarker().hideInfoWindow();
        }

        mObjMarkerMap.put(obj.getId(), marker);
        mObjLastLatlngMap.put(obj.getId(), new Node(new LatLng(obj.getLat(), obj.getLng())));
    }

    /**
     * 添加移动小车
     *
     * @param obj
     */
    public void moveCar(Car obj, AMap map) {
        if (obj == null) {
            return;
        }

        //判断汽车是否已经存在，不存在的话先添加汽车
        if (!mObjMarkerMap.containsKey(obj.getId())) {
            addCar(obj, map);
            return;
        }

        if (mObjMarkerMap.containsKey(obj.getId())) {
            SmoothMoveMarker marker = mObjMarkerMap.get(obj.getId());

            List<LatLng> points = new ArrayList<>();
            LatLng start = mObjLastLatlngMap.get(obj.getId()).latLng;
            LatLng end = new LatLng(obj.getLat(), obj.getLng());

            // 防止抖动
            float minDistance = AMapUtils.calculateLineDistance(start, end);
            if (minDistance < 1f) {
                if (obj.isShowInfoWindow()) {
                    marker.getMarker().showInfoWindow();
                }
                marker.getMarker().setObject(obj);
                return;
            }

            // 滑动过程均分
            for (int i = 0; i <= DEF_CAR_ANIMATION_FRAME_COUNT; i++) {
                double lat = start.latitude + (end.latitude - start.latitude) * i / DEF_CAR_ANIMATION_FRAME_COUNT;
                double lng = start.longitude + (end.longitude - start.longitude) * i / DEF_CAR_ANIMATION_FRAME_COUNT;
                points.add(new LatLng(lat, lng));
            }

            // 设置滑动的轨迹左边点
            marker.setPoints(points);
            // 设置滑动的总时间(单位 s)
            marker.setTotalDuration(DEF_CAR_ANIMATION_FRAME_COUNT);
            // 开始滑动
            marker.startSmoothMove();
            marker.getMarker().setObject(obj);

            Node node = mObjLastLatlngMap.get(obj.getId());
            node.latLng = new LatLng(obj.getLat(), obj.getLng());
            mObjLastLatlngMap.put(obj.getId(), node);
        }
    }

    /**
     * 移除指定的小车
     *
     * @param carId
     */
    public void removeCar(String carId) {
        if (mObjMarkerMap.containsKey(carId)) {
            SmoothMoveMarker marker = mObjMarkerMap.get(carId);
            mObjMarkerMap.remove(carId);
            mObjLastLatlngMap.remove(carId);
            if (marker != null) {
                marker.getMarker().remove();
            }
        }
    }

    /**
     * 移除所有的小车
     */
    public void removeCars() {
        for (Map.Entry<String, SmoothMoveMarker> entry : mObjMarkerMap.entrySet()) {
            entry.getValue().getMarker().remove();
        }
        mObjMarkerMap.clear();
        mObjLastLatlngMap.clear();
    }

    private class Node {
        Node(LatLng latLng) {
            this.latLng = latLng;
        }

        long updateTime;
        LatLng latLng;
    }

    /**
     * 移动到指定的可视区域
     *
     * @param start        起点坐标
     * @param end          终点坐标
     * @param marginTop    与地图上边距
     * @param marginBottom 与地图下边距
     * @param marginLeft   与地图左边距
     * @param marginRight  与地图右边距
     */
    public static void moveTovisibleArea(AMap aMap, LatLng start, LatLng end, int marginTop, int marginBottom, int marginLeft, int marginRight) {
        LatLngBounds.Builder boundsBuilder = LatLngBounds.builder();
        boundsBuilder.include(start);
        boundsBuilder.include(end);
        aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(boundsBuilder.build(),
                marginTop, marginBottom, marginLeft, marginRight), 500, null);
    }

    private static Marker myLocationMarker;

    public static void setNaviOptions(Context context, AMap map, AMapNaviView aMapNaviView, UserRepository userRepository) {
        UiSettings settings = map.getUiSettings();
        settings.setRotateGesturesEnabled(false);
        settings.setTiltGesturesEnabled(false);
        settings.setCompassEnabled(false);
        /*设置车标*/
        AMapNaviViewOptions options = aMapNaviView.getViewOptions();
        Bitmap transparentBitmap = null;
        if (AppConfig.isTaxi()) {//出租车业务
            options.setCarBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.chuzuche_map_icon_car));
            transparentBitmap = ImageUtil.getTransparentBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.chuzuche_map_icon_car), 0);
        } else if (AppConfig.isSpecial()) {//专车业务
            if (userRepository.getDriverType() == DriverType.SPECIAL) {//专车司机
                options.setCarBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.map_icon_car));
                transparentBitmap = ImageUtil.getTransparentBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.map_icon_car), 0);
            }
        }
        options.setTilt(0);
        options.setLayoutVisible(false);
        options.setFourCornersBitmap(transparentBitmap);
        options.setStartPointBitmap(transparentBitmap);
        options.setEndPointBitmap(transparentBitmap);
        //关闭自动绘制路线（如果你想自行绘制路线的话，必须关闭！！！）
        options.setAutoDrawRoute(true);
        //主动隐藏蚯蚓线
        options.setLaneInfoShow(true);
        options.setRouteListButtonShow(false);
        options.setCompassEnabled(false);
        options.setTrafficBarEnabled(false);//设置路况光柱条是否显示（只适用于驾车导航，需要联网）
        options.setScreenAlwaysBright(true);//屏幕常亮
        options.setCameraBubbleShow(false);
        options.setAutoChangeZoom(false);
        options.setZoom(15);
        aMapNaviView.setViewOptions(options);
    }

    /**
     * 设置起点Marker
     */
    public static Marker setOriginMarker(Context context, LatLng latLng, AMap aMap) {
        return aMap.addMarker(new MarkerOptions().
                position(latLng).
                title("起点").
                icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(
                                context.getResources(), R.drawable.public_pic_qidian))));
    }

    /**
     * 设置终点Marker
     */
    public static Marker setEndMarker(Context context, LatLng latLng, AMap aMap) {
        return aMap.addMarker(new MarkerOptions().
                position(latLng).
                title("终点").
                icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(
                                context.getResources(), R.drawable.public_pic_zhongdian))));
    }

    /**
     * 设置终点Marker
     */
    public static void setMyLocationMarker(Context context, LatLng latLng, AMap aMap) {
        myLocationMarker = aMap.addMarker(new MarkerOptions().
                position(latLng).
                title("我的位置").
                icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(
                                context.getResources(), R.drawable.map_icon_car))));
    }

    public static Marker getMyLocationMarker() {
        return myLocationMarker;
    }


    public static void initAnim(View v) {
        RotateAnimation animation = new RotateAnimation(0, 360, v.getPivotX(), v.getPivotY());
        animation.setInterpolator(new LinearInterpolator()); // 匀速旋转
        animation.setRepeatCount(Animation.INFINITE); // 无限重复
        animation.setDuration(500);
        v.setAnimation(animation);
        animation.setRepeatMode(Animation.RESTART);
        animation.start();
    }


    // 把LatLonPoint对象转化为LatLon对象
    public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
    }

    public static LatLonPoint convertToPoint(LatLng latLng) {
        return new LatLonPoint(latLng.latitude, latLng.longitude);
    }

    public static NaviLatLng convertToNavi(LatLng latLng) {
        return new NaviLatLng(latLng.latitude, latLng.longitude);
    }

    public static NaviLatLng convertToNavi(LatLonPoint latLng) {
        return new NaviLatLng(latLng.getLatitude(), latLng.getLongitude());
    }

    public static LatLng convertNaviToLatLng(NaviLatLng latLng) {
        return new LatLng(latLng.getLatitude(), latLng.getLongitude());
    }

    public static LatLonPoint convertNaviToPoint(NaviLatLng latLng) {
        return new LatLonPoint(latLng.getLatitude(), latLng.getLongitude());
    }

}
